// stores/user.js
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'
import api from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: localStorage.getItem('token') || '',
    permissions: [],
    roles: []
  }),

  getters: {
    // 判断用户是否登录
    isLoggedIn: (state) => !!state.token,

    // 判断用户是否有权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },

    // 判断用户是否有角色
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    },

    // 获取用户姓名
    userName: (state) => {
      return state.userInfo?.username || state.userInfo?.name || '未知用户'
    }
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.roles = userInfo.roles || []
      this.permissions = userInfo.permissions || []
    },

    // 设置Token
    setToken(token) {
      this.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },

    // 登录
    async login(credentials) {
      try {
        // 调用API登录
        const response = await api.post('/auth/login', credentials)
        const { access_token, user } = response.data
        
        this.setToken(access_token)
        this.setUserInfo(user)
        
        return response.data
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    // 注册
    async register(registrationData) {
      try {
        const response = await api.post('/auth/register', registrationData)
        return response.data
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    // 退出登录
    logout() {
      this.setToken('')
      this.setUserInfo(null)
      this.permissions = []
      this.roles = []
    },

    // 检查权限（用于路由守卫）
    checkPermission(requiredRoles) {
      if (!requiredRoles || requiredRoles.length === 0) {
        return true
      }
      return requiredRoles.some(role => this.hasRole(role))
    }
  },

  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token'] // 只持久化token
  }
})